package org.example.springbootpra1.demos.controller;

import com.alibaba.excel.EasyExcel;
import org.example.springbootpra1.demos.bean.ChargeAccountRule;
import org.example.springbootpra1.demos.bean.ChargePlot;
import org.example.springbootpra1.demos.listener.ChargeAccountRuleListener;
import org.example.springbootpra1.demos.services.service.ChargeAccountRuleService;
import org.example.springbootpra1.demos.services.service.ChargePileService;
import org.example.springbootpra1.demos.services.service.ChargePlotService;
import org.example.springbootpra1.demos.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * 充电站Controller
 *
 * @author zdcloud
 * @date 2024-09-18
 */
@RestController
@RequestMapping("/import")
public class ImportController
{
    @Autowired
    private ChargeAccountRuleService chargeAccountRuleService;

    /**
     * 基于Listener方式从Excel导入会员列表
     */
    @RequestMapping(value = "/chargeAccountRule", method = RequestMethod.POST)
    @ResponseBody
    public Result<Void> importMemberList2(@RequestPart("file") MultipartFile file) throws IOException {
        // 方式一：同步读取，将解析结果返回，比如返回List<Member>，业务再进行相应的数据集中处理
        // 方式二：对照doReadSync()方法的是最后调用doRead()方法，不进行结果返回，而是在ChargeAccountRuleListener中进行一条条数据的处理；
        // 此处示例为方式二
//        EasyExcel.read(file.getInputStream(), ChargeAccountRule.class, new ChargeAccountRuleListener(chargeAccountRuleService)).sheet().doRead();

//        String resultStr = chargeAccountRuleService.uploadChargeAccountRules(file);
//
//        if (resultStr != null){
//            return Result.error(resultStr);
//        }
//        return Result.Success("上传成功");


        // 创建一个新的 ChargeAccountRuleListener 实例
        ChargeAccountRuleListener listener = new ChargeAccountRuleListener(chargeAccountRuleService);
        EasyExcel.read(file.getInputStream(), ChargeAccountRule.class, listener).sheet().doRead();

        // 获取错误信息
        List<String> errorMsgList = listener.getErrorMsgList();
        if (!errorMsgList.isEmpty()) {
            StringBuilder errorMessages = new StringBuilder();
            for (String errorMsg : errorMsgList) {
                errorMessages.append(errorMsg).append("\n");
            }
//            log.error("上传过程中发现以下错误:\n{"+errorMessages.toString()+"}");
            return Result.error("上传过程中发现以下错误:\n{"+errorMessages.toString()+"}");
        }
        return Result.Success("上传成功");

    }


}